package Controller

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"hr-system/Global"
	"hr-system/Model"
	response "hr-system/Response"
	"strconv"
)

type IPostManageController interface {
	RestController
	Update(c *gin.Context)
	Delete(c *gin.Context)
}

type PostManageController struct {
	DB *gorm.DB
}

func NewPostManageController() IPostManageController{
	db := Global.GetDB()
	return PostManageController{DB: db}
}

func (p PostManageController) PageList(c *gin.Context) {
	var requestDepartment Model.Department
	_ = c.ShouldBind(&requestDepartment)
	name := requestDepartment.DepartmentName
	if name != "" {
		var selectPost []Model.Post

		// 查询
		err := p.DB.Where("post_name=?", name).Find(&selectPost).Error
		if err != nil {
			response.Fail(c, err.Error(), nil)
			return
		}
		response.Success(c, gin.H{"data": selectPost}, "查询成功")
		return
	}
	var posts []Model.Post
	p.DB.Order("post_number").Find(&posts)
	re := make([]Model.ReturnPost, 0)
	length := len(posts)
	for i := 0; i<length; i++ {
		post := posts[i]
		var temp Model.Department
		p.DB.Where("department_number=?",post.DepartmentNumber).First(&temp)
		re = append(re, Model.ReturnPost{
			UniPost: post.UniPost,
			DepartmentName: temp.DepartmentName,
		})
	}
	response.Success(c, gin.H{"data": re}, "查询成功")
}

func (p PostManageController) Create(c *gin.Context) {
	var requestPost Model.Post
	_ = c.ShouldBind(&requestPost)
	result := p.DB.Where("post_number=?", requestPost.PostNumber).First(&Model.Post{}).RowsAffected
	if result != 0 {
		response.Fail(c, "岗位号已存在", nil)
		return
	}
	err := p.DB.Create(&requestPost).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	response.Success(c, gin.H{"data": requestPost} , "创建成功")
}

func (p PostManageController) Update(c *gin.Context) {
	// 绑定body中参数（更新后的值）
	var requestPost Model.Post
	_ = c.ShouldBind(&requestPost)
	id := requestPost.PostNumber
	// 更新
	err := p.DB.Model(&Model.Post{}).Where("post_number=?", id).Updates(&requestPost).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	response.Success(c, gin.H{"data": requestPost}, "修改成功")
}

func (p PostManageController) Delete(c *gin.Context) {
	idStr, _ := c.GetPostForm("post_number")
	id, _ := strconv.Atoi(idStr)
	// 查询
	result := p.DB.Where("post_number=?",id).First(&Model.Post{}).RowsAffected
	if result == 0 {
		response.Fail(c, "岗位不存在", nil)
		return
	}
	// 删除
	err := p.DB.Where("post_number=?", id).Delete(&Model.Post{}).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	response.Success(c, nil, "删除成功")
}
